// 如果你想让这个组件成为客户端组件：  
'use client';
import { useEffect, useMemo, useRef, useState } from "react";
import { Affix, Button, message } from 'antd'
import { ButtonEnum, generateDireaction, generateWeightedRandomNumber, getRandomPoint, renderE } from "../utils/tool";
import useGamePad from "../gamepade/useGamePad";

const Max = 100;
const Min = 10;
type TestItem = {
    direction: string, size: number
}

// 手柄链接
// 测试开始
export default function Dom() {
    const { timestamp, button } = useGamePad();
    const size = useRef(50);
    const direction: any = useRef();
    const position: any = useRef();
    const testList = useRef<Array<TestItem>>([]);
    const feedbackList = useRef<Array<TestItem & { correct: boolean }>>([]);
    var { context, canvas } = useMemo(() => {
        if (window && document && document.getElementById('blackRectangle')) {
            const _canvas = document.getElementById('blackRectangle') as HTMLCanvasElement;;
            // 设置canvas的宽度和高度  
            _canvas.width = window.innerWidth;
            _canvas.height = window.innerHeight;
            return { canvas: _canvas, context: _canvas.getContext('2d') as CanvasRenderingContext2D }
        }
        return {}
    }, []);
    const [state, _setState] = useState({
        begin: false,
        mode: '',
    });
    const setState = (params: { [key: string]: any }) => {
        _setState((_state) => ({ ..._state, ...params }));
    };
    const { begin, mode } = state;
    // 确保渲染上下文与canvas的尺寸匹配  
    // context.scale(canvas.width / window.innerWidth, canvas.height / window.innerHeight);

    function getE(_size?: number, _direction?: string, _position?: { x: number, y: number }) {
        _size =  _size || generateWeightedRandomNumber(Min, Max);
        _direction = _direction || generateDireaction();
        _position = _position || getRandomPoint(_size);
        testList.current.push({
            direction: _direction,
            size: _size
        })
        size.current = _size;
        direction.current = _direction
        position.current = _position
        renderE(_size, _direction, _position, { context, canvas } as any)
    }
    useEffect(() => {
        if (button == ButtonEnum.START) {
            setState({
                begin: true,
                mode: 'dynamic'
            })
            setTimeout(() => {
                getE(Max)
            }, 1000);
        } else if (testList.current.length) {
            let currentE = testList.current[testList.current.length - 1];
            if ([ButtonEnum.A, ButtonEnum.B, ButtonEnum.X, ButtonEnum.Y].includes(button)) {
                let lastFeed = feedbackList.current[feedbackList.current.length - 1];
                let correct = currentE.direction == ({ [ButtonEnum.Y]: '上', [ButtonEnum.A]: '下', [ButtonEnum.X]: '左', [ButtonEnum.B]: '右', })[button]
                feedbackList.current.push({
                    ...currentE,
                    correct: correct
                });
                if(mode == 'test'){
                    if (currentE.direction == ({ [ButtonEnum.Y]: '上', [ButtonEnum.A]: '下', [ButtonEnum.X]: '左', [ButtonEnum.B]: '右', })[button]) {
                        getE(lastFeed?.correct === false ? size.current : size.current - 1);
                    } else {
                        message.open({
                            icon: null,
                            content: <span style={{ fontSize: '50px' }}>{currentE.size}, {currentE.direction}</span>
                        })
                        getE(size.current + 1)
                    }
                }
                else {
                    getE()
                }
                
            }
            if ([ButtonEnum.LEFT, ButtonEnum.BOTTOM, ButtonEnum.TOP, ButtonEnum.RIGHT].includes(button) && testList.current.length) {
                getE(size.current)
            }
            if (button == ButtonEnum.CIRCLEL) {
                getE(size.current + 1, direction.current, position.current)
            }
            if (button == ButtonEnum.CIRCLER) {
                getE(size.current - 1, direction.current, position.current)
            }
            if (button == ButtonEnum.SELECT) {
                message.open({
                    icon: null,
                    content: <span style={{ fontSize: '200px' }}>{currentE.size}, {currentE.direction}</span>
                })
            }
            if(button == ButtonEnum.R2){
                message.open({
                    icon: null,
                    content: <span style={{ fontSize: '200px' }}>您做对{feedbackList.current.filter(item => item.correct)?.length}个， 错了{feedbackList.current.filter(item => item.correct === false)?.length}个</span>
                })
            }
            if(button == ButtonEnum.L2){
                location.reload()
            }
        }
    }, [timestamp])
    return <>
        {begin ? <> </> : <div style={{ textAlign: 'center', position: 'absolute', top: '1rem', zIndex: 1 }}>
            <Button size="large" type="primary" onClick={() => {
                setState({
                    begin: true,
                    mode: 'test'
                })
                setTimeout(() => {
                    getE(Max)
                }, 1000);
            }}>开始测试</Button>
        </div>}
    </>
}